﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ufida.u9.ait.openapi.utils
{
    /// <summary>
    /// 反射工具
    /// </summary>
    public static class ReflexUtils
    {
        /// <summary>
        /// 判断对象是否包含某属性
        /// </summary>
        /// <param name="fieldName"></param>
        /// <param name="obj"></param>
        public static bool HasField(string fieldName,object obj)
        {
            object val = GetObjectValue(fieldName, obj);
            if (val==null)
                return false;
            else
                return true;
        }

        /// <summary>
        /// 取对象属性值
        /// </summary>
        /// <param name="FieldName">字段名</param>
        /// <param name="obj">对象</param>
        /// <returns>对象属性</returns>
        public static string GetValue(string FieldName, object obj)
        {
            try
            {
                object o = GetObjectValue(FieldName, obj);
                if (null == o)
                    return "";
                string str = Convert.ToString(o);
                return str;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 通过反射,获取对象属性
        /// </summary>
        /// <param name="FieldName">字段名</param>
        /// <param name="obj">对象</param>
        /// <returns>对象属性</returns>
        public static object GetObjectValue(string FieldName, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                System.Reflection.PropertyInfo prop = Ts.GetProperty(FieldName);
                if (prop == null)
                {
                    return null;
                }
                object o = prop.GetValue(obj, null);
                return o;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 设置对象属性值
        /// </summary>
        /// <param name="FieldName"></param>
        /// <param name="Value"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool SetValue(string FieldName, string Value, object obj)
        {
            try
            {
                Type Ts = obj.GetType();
                object v = Convert.ChangeType(Value, Ts.GetProperty(FieldName).PropertyType);
                Ts.GetProperty(FieldName).SetValue(obj, v, null);
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


    }


}
